﻿using System;
using System.Collections.Generic;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using DevExpress.XtraEditors;
using XCT.Class;
using XCT.Functions;

namespace XCT.Forms
{
    public partial class FormDBG : DevExpress.XtraEditors.XtraForm
    {
        public FormDBG()
        {
            InitializeComponent();
        }

        private FormMain formMain;
        public FormDBG(FormMain formMain)
        {
            InitializeComponent();
            this.formMain = formMain;
        }

        #region "Biến"

        clsDBG clsdbg = new clsDBG();
        clsDungChung clsdc = new clsDungChung();
        string pTuanKH, pMaMau_SP = "";
        int intTrangThai = -1; // 0:Them, 1:Sua, 2:Xoa
        DataSet dtsNhapDBG, dtsXemDBG;
               
        #endregion

        #region "Sự Kiện"

        #region "Dùng Chung"

        private void FormDBG_Load(object sender, EventArgs e)
        {
            fKhoiTaoComBo();
        }

        private void FormDBG_FormClosed(object sender, FormClosedEventArgs e)
        {
            formMain.pFormDBG = null;
        }

        private void FormDBG_KeyDown(object sender, KeyEventArgs e)
        {
            try
            {
                if (e.Modifiers == Keys.Control)
                {
                    switch (e.KeyCode)
                    {
                        case Keys.S:
                            if (tabDBG.SelectedTabPage.Name == "tabDBG1")
                            {
                                if (intTrangThai != -1)
                                    if (XtraMessageBox.Show("Bạn có chắc muốn lưu không ?", "Thông tin lưu ý: ", MessageBoxButtons.YesNo) == DialogResult.Yes)
                                    {
                                        grdNhapDBG_View.FocusedRowHandle = grdNhapDBG_View.FocusedRowHandle + 1;
                                        grdNhapDBG_View.CloseEditor();
                                        if (fLuuDBG() == true)
                                        {
                                            XtraMessageBox.Show("Lưu thành công !", "Thông báo:");
                                            intTrangThai = -1;
                                            fDocChietTinhDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
                                        }
                                        else
                                        {
                                            XtraMessageBox.Show("Không thể lưu, vui lòng kiểm tra lại dữ liệu nhập!");
                                        }
                                    }
                            }
                            return;
                        case (Keys.E):
                            if (tabDBG.SelectedTabPage.Name == "tabDBG1")
                            {
                                if (intTrangThai == -1 || intTrangThai == 1)
                                {
                                    ArrayList arr = new ArrayList();
                                    arr.Add("SL_Nhap_Ca1"); //cột sản lượng ca A
                                    arr.Add("SL_Nhap_Ca2"); //cột sản lượng ca B
                                    arr.Add("SL_Nhap_Ca3"); //cột sản lượng ca C
                                    arr.Add("GhiChu"); //ghi chú

                                    clsdc.editGrid(grdNhapDBG_View, true, arr);
                                    fMoKhoaControl(false);

                                    intTrangThai = 1;
                                    lblMsg.Text = "Bạn đang ở chế độ sửa, vui lòng nhấn [Ctrl+S] để lưu !"; lblMsg.Visible = true;
                                }
                                else
                                {
                                    XtraMessageBox.Show("Bạn phải lưu trước khi chuyển thao tác mới...", "Thông Báo:");
                                }
                            }
                            return;
                        case (Keys.P):
                            if (XtraMessageBox.Show("Bạn có chắc muốn xuất ra tập tin Excel ?", "Thông tin lưu ý: ", MessageBoxButtons.YesNo) == DialogResult.Yes) 
                                XuatTapTinExcel(tabDBG.SelectedTabPage.Name);
                            return;
                    }
                }
                else if (e.KeyCode == Keys.F5)
                {
                    intTrangThai = -1;
                    if (tabDBG.SelectedTabPage.Name == "tabDBG1")
                    {
                        fDocChietTinhDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
                    }
                }
                else if (e.KeyCode == Keys.Escape)
                {
                    this.Close();
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
        }

        //Sự kiện SelectedIndexChanged của cmbTuanKH, cmbThangKH, cmbNamKH
        private void cmbNamKH_SelectedIndexChanged(object sender, EventArgs e)
        {
            pTuanKH = cmbTuanKH.Text + cmbThangKH.Text + cmbNamKH.Text;
            if (tabDBG.SelectedTabPage.Name == "tabDBG1")
            {
                fDocLSXTheoTuanKH(pTuanKH);
                //fDocMauChietTinhTheoLSX(lupLSX.Text);
                //fDocChietTinhDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
            }
            else if (tabDBG.SelectedTabPage.Name == "tabDBG2")
            {
                fDocLSX_DBGTheoTuanKH(pTuanKH);
                //fDocMauSP_DBGTheoLSX(lupLSX.Text);
                //fDocDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP);
            }
            lupLSX_EditValueChanged(sender, e);
        }

        //Tìm LSX
        private void txtTimLSX_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
            {
                if (txtTimLSX.Text.Length > 0)
                {
                    DataSet ds = new DataSet();
                    clsdbg.SoLSX = txtTimLSX.Text.Trim();
                    ds = clsdbg.TimLSX(tabDBG.SelectedTabPage.Name);
                    lupLSX.Properties.DataSource = ds.Tables[0].DefaultView;
                    lupLSX.Properties.ValueMember = "SoLSX";
                    lupLSX.Properties.DisplayMember = "SoLSX";
                    lupLSX.ItemIndex = 0;
                    lupLSX_EditValueChanged(sender, e);

                    if (lupLSX.ItemIndex != -1)
                    {
                        cmbTuanKH.EditValue = lupLSX.GetColumnValue("TTN").ToString().Substring(0, 2);
                        cmbThangKH.EditValue = lupLSX.GetColumnValue("TTN").ToString().Substring(2, 2);
                        cmbNamKH.EditValue = lupLSX.GetColumnValue("TTN").ToString().Substring(4, 4);
                    }
                }
            }
        }

        //Sự kiện EditValueChanged của lupLSX
        private void lupLSX_EditValueChanged(object sender, EventArgs e)
        {
            if (lupLSX.ItemIndex == -1)
                lblMaSP.Text = "Mã sản phẩm";
            else
                lblMaSP.Text = lupLSX.GetColumnValue("MaSP").ToString();

            if (tabDBG.SelectedTabPage.Name == "tabDBG1")
            {
                fDocMauChietTinhTheoLSX(lupLSX.Text);
                fDocChietTinhDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
            }
            else if (tabDBG.SelectedTabPage.Name == "tabDBG2")
            {
                fDocMauSP_DBGTheoLSX(lupLSX.Text);
                fDocDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP);
            }
        }

        private void chkEdtMauSP_CheckedChanged(object sender, EventArgs e)
        {
            chkLstMauSP.BeginUpdate();
            try
            {
                for (int i = 0; i < chkLstMauSP.ItemCount; i++)
                {
                    chkLstMauSP.SetItemCheckState(i, chkEdtMauSP.CheckState);
                }
            }
            finally
            {
                chkLstMauSP.EndUpdate();
            }
        }

        //Sự kiện check list box
        private void chkLstMauSP_ItemCheck(object sender, DevExpress.XtraEditors.Controls.ItemCheckEventArgs e)
        {
            fLayGiaTriMauSP();
            if (tabDBG.SelectedTabPage.Name == "tabDBG1")
            {
                fDocChietTinhDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
            }
            else if (tabDBG.SelectedTabPage.Name == "tabDBG2")
            {
                fDocDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP);
            }
        }

        //Sự kiện kiểm tra Tab trước khi chuyển Tab
        private void tabDBG_SelectedPageChanging(object sender, DevExpress.XtraTab.TabPageChangingEventArgs e)
        {
            if (intTrangThai != -1)
            {
                XtraMessageBox.Show("Vui lòng nhấn [Ctrl+S] để lưu trước khi chuyển tab ...", "Thông Báo:");
                e.Cancel = true;
            }
        }        

        //Sự kiện chuyển Tab
        private void tabDBG_SelectedPageChanged(object sender, DevExpress.XtraTab.TabPageChangedEventArgs e)
        {
            txtTimLSX.Text = "";
            lblMaSP.Text = "Mã sản phẩm";
            cmbNamKH_SelectedIndexChanged(sender, e);
            if (tabDBG.SelectedTabPage.Name == "tabDBG1")
            {
                dteNgayTH.Visible = true;
                labelNgayTH.Visible = true;
                //fDocLSXTheoTuanKH(pTuanKH);
                //fDocMauChietTinhTheoLSX(lupLSX.Text);
                //fDocChietTinhDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
            }
            else if (tabDBG.SelectedTabPage.Name == "tabDBG2")
            {
                dteNgayTH.Visible = false;
                labelNgayTH.Visible = false;
                //fDocLSX_DBGTheoTuanKH(pTuanKH);
                //fDocMauSP_DBGTheoLSX(lupLSX.Text);
                //fDocDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP);
            }
        }

        #endregion

        #region "tabDBG1"

        //Sự kiện EditValueChanged dteNgayTH
        private void dteNgayTH_EditValueChanged(object sender, EventArgs e)
        {
            fDocChietTinhDBGTheoLSX_MauSP(lupLSX.Text, pMaMau_SP, dteNgayTH.Text);
        }

        private void repositoryItemSpinEdit1_KeyPress(object sender, KeyPressEventArgs e)
        {
            if (e.KeyChar == '-')
            {
                e.Handled = true;
            }
        }

        private void grdNhapDBG_View_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            float ThucHien, LuyKe, SL_Nhap_Ca1 = 0, SL_Nhap_Ca2 = 0, SL_Nhap_Ca3 = 0;
            LuyKe = float.Parse(dtsNhapDBG.Tables[0].Rows[e.RowHandle]["LuyKe"].ToString());
            if (dtsNhapDBG.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca1"].ToString() != "")
                SL_Nhap_Ca1 = float.Parse(dtsNhapDBG.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca1"].ToString());
            if (dtsNhapDBG.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca2"].ToString() != "")
                SL_Nhap_Ca2 = float.Parse(dtsNhapDBG.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca2"].ToString());
            if (dtsNhapDBG.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca3"].ToString() != "")
                SL_Nhap_Ca3 = float.Parse(dtsNhapDBG.Tables[0].Rows[e.RowHandle]["SL_Nhap_Ca3"].ToString());
            ThucHien = float.Parse(dtsNhapDBG.Tables[0].Rows[e.RowHandle]["ThucHien"].ToString());

            if (LuyKe + SL_Nhap_Ca1 + SL_Nhap_Ca2 + SL_Nhap_Ca3 > ThucHien)
            {
                XtraMessageBox.Show("Bạn nhập vượt quá kế hoạch thực hiện !");
                grdNhapDBG_View.SetFocusedValue(0);
                grdNhapDBG_View.FocusedColumn = grdNhapDBG_View.VisibleColumns[grdNhapDBG_View.FocusedColumn.VisibleIndex - 1];
            }
        }

        #endregion

        #region "tabDBG2"


        #endregion

        #endregion

        #region "Hàm"

        #region "Dùng Chung"

        private void fMoKhoaControl(Boolean bisMoKhoa)
        {
            cmbTuanKH.Enabled = bisMoKhoa;
            cmbThangKH.Enabled = bisMoKhoa;
            cmbNamKH.Enabled = bisMoKhoa;
            lupLSX.Enabled = bisMoKhoa;
            dteNgayTH.Enabled = bisMoKhoa;
            txtTimLSX.Enabled = bisMoKhoa;
            chkEdtMauSP.Enabled = bisMoKhoa;
            chkLstMauSP.Enabled = bisMoKhoa;
        }

        private void fKhoiTaoComBo()
        {
            for (int i = 2010; i <= DateTime.Now.Year + 1; i++)
                cmbNamKH.Properties.Items.Add(i.ToString());
            cmbNamKH.Text = DateTime.Now.Year.ToString();
            cmbThangKH.SelectedIndex = DateTime.Now.Month - 1;
            dteNgayTH.DateTime = DateTime.Now;
            pTuanKH = cmbTuanKH.Text + cmbThangKH.Text + cmbNamKH.Text;
        }

        private void fLayGiaTriMauSP()
        {
            pMaMau_SP = "";
            int i = 0;
            while (chkLstMauSP.GetItem(i) != null)
            {
                if (chkLstMauSP.GetItemChecked(i) == true)
                {
                    if (string.IsNullOrEmpty(pMaMau_SP) == false)
                        pMaMau_SP = pMaMau_SP + "','";
                    pMaMau_SP = pMaMau_SP + chkLstMauSP.GetItemValue(i);
                }
                i++;
            }
        }

        private void XuatTapTinExcel(string tabName)
        {
            SaveFileDialog saveDlg;
            try
            {
                saveDlg = new SaveFileDialog();
                saveDlg.InitialDirectory = "C:\"";
                saveDlg.Filter = "Excel Files|*.xls";
                saveDlg.FilterIndex = 2;
                if (saveDlg.ShowDialog() == DialogResult.OK)
                {
                    if (tabName == "tabDBG1")
                    {
                        DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                        grdNhapDBG_View.ExportToXls(saveDlg.FileName, options);
                    }
                    else if (tabName == "tabDBG2")
                    {
                        DevExpress.XtraPrinting.XlsExportOptions options = new DevExpress.XtraPrinting.XlsExportOptions();
                        grdXemDBG_View.ExportToXls(saveDlg.FileName, options);
                    }
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
                saveDlg = null;
            }
        }

        #endregion

        #region "tabDBG1"

        //Đọc SoLSX của điều phối theo tuần KH
        private void fDocLSXTheoTuanKH(string TuanKH)
        {
            DataSet ds = new DataSet();
            ds = clsdbg.DocLSXTheoTuanKH(TuanKH);
            lupLSX.Properties.DataSource = ds.Tables[0].DefaultView;
            lupLSX.Properties.ValueMember = "SoLSX";
            lupLSX.Properties.DisplayMember = "SoLSX";
        }

        //Đọc ma mau chiết tính theo lệnh sản xuất
        private void fDocMauChietTinhTheoLSX(string SoLSX)
        {
            clsdbg.SoLSX = SoLSX;
            DataSet ds = new DataSet();
            ds = clsdbg.DocMauChietTinhTheoLSX();
            chkLstMauSP.DataSource = ds.Tables[0].DefaultView;
            chkLstMauSP.ValueMember = "MaMau_SP";
            chkLstMauSP.DisplayMember = "TenMau_SP";
            pMaMau_SP = "";
        }

        //Đọc chiết tính theo lệnh sản xuất, ngày thực hiện
        private void fDocChietTinhDBGTheoLSX_MauSP(string SoLSX, string MaMau_SP, string NgayTH)
        {
            dtsNhapDBG = new DataSet();
            clsdbg.SoLSX = SoLSX;
            clsdbg.MaMau_SP = MaMau_SP;
            dtsNhapDBG = clsdbg.DocChietTinhDBGTheoLSX(NgayTH);
            grdNhapDBG.DataSource = dtsNhapDBG.Tables[0].DefaultView;

            lblMsg.Visible = false;

            fMoKhoaControl(true);
            clsdc.editGrid(grdNhapDBG_View, false, null);
        }

        // Lưu DBG theo trạng thái
        private Boolean fLuuDBG()
        {
            try
            {
                switch (intTrangThai)
                {
                    case 1: //trang thai = 1: sửa
                        if (dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows.Count > 0)
                        {
                            for (int intRow = 0; intRow < dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows.Count; intRow++)
                            {
                                clsdbg = new clsDBG();
                                clsdbg.SoLSX = lupLSX.EditValue.ToString();
                                clsdbg.MaChietTinhML = int.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaChietTinhML"].ToString());
                                clsdbg.MaSP = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaSP"].ToString();
                                clsdbg.NgayTH = Convert.ToDateTime(dteNgayTH.DateTime.ToShortDateString());
                                clsdbg.SLKH = float.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["ThucHien"].ToString());
                                if (dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca1"].ToString() != "")
                                    clsdbg.SL_Nhap_Ca1 = float.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca1"].ToString());
                                if (dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca2"].ToString() != "")
                                    clsdbg.SL_Nhap_Ca2 = float.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca2"].ToString());
                                if (dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca3"].ToString() != "")
                                    clsdbg.SL_Nhap_Ca3 = float.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["SL_Nhap_Ca3"].ToString());
                                clsdbg.Tong_SL_Nhap = clsdbg.SL_Nhap_Ca1 + clsdbg.SL_Nhap_Ca2 + clsdbg.SL_Nhap_Ca3;
                                clsdbg.MaChungLoai_Mousse = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaChungLoai_Mousse"].ToString();
                                clsdbg.MaMau_Mousse = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaMau_Mousse"].ToString();
                                clsdbg.DoLy = float.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["DoLy"].ToString());
                                clsdbg.QuiCach = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["QuiCach"].ToString();
                                clsdbg.MaMau_SP = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaMau_SP"].ToString();
                                clsdbg.CoSoID = int.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["CoSoID"].ToString());
                                clsdbg.MaHoaVan_Mousse = int.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaHoaVan_Mousse"].ToString());
                                clsdbg.DvtID = int.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["DVTID"].ToString());
                                clsdbg.MaCD = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["MaCD"].ToString();
                                clsdbg.DinhMuc = float.Parse(dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["DinhMuc"].ToString());
                                clsdbg.DoShore = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["DoShore"].ToString();
                                clsdbg.GhiChuChiTiet = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["GhiChuChiTiet"].ToString();
                                clsdbg.GhiChu = dtsNhapDBG.Tables[0].GetChanges(DataRowState.Modified).Rows[intRow]["GhiChu"].ToString();
                                clsdbg.UserUpdate = clsDungChung.strUser;

                                if (clsdbg.LuuDBG() == false)
                                    return false;
                            }
                            return true;
                        }
                        return true;
                    default:
                        return true;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        #endregion

        #region "tabDBG2"

        //Đọc SoLSX của DBG theo tuần KH
        private void fDocLSX_DBGTheoTuanKH(string TuanKH)
        {
            DataSet ds = new DataSet();
            ds = clsdbg.DocLSX_DBGTheoTuanKH(TuanKH);
            lupLSX.Properties.DataSource = ds.Tables[0].DefaultView;
            lupLSX.Properties.ValueMember = "SoLSX";
            lupLSX.Properties.DisplayMember = "SoLSX";
        }

        //Đọc màu SP của DBG theo tuần KH
        private void fDocMauSP_DBGTheoLSX(string SoLSX)
        {
            DataSet ds = new DataSet();
            clsdbg.SoLSX = SoLSX;
            ds = clsdbg.DocMauSP_DBGTheoLSX();
            chkLstMauSP.DataSource = ds.Tables[0].DefaultView;
            chkLstMauSP.ValueMember = "MaMau_SP";
            chkLstMauSP.DisplayMember = "TenMau_SP";
            pMaMau_SP = "";
        }

        //Đọc DBG theo lệnh sản xuất, Màu SP
        private void fDocDBGTheoLSX_MauSP(string SoLSX, string MaMau_SP)
        {
            dtsXemDBG = new DataSet();
            clsdbg.SoLSX = SoLSX;
            clsdbg.MaMau_SP = MaMau_SP;
            dtsXemDBG = clsdbg.DocDBGTheoLSX_MauSP();
            grdXemDBG.DataSource = dtsXemDBG.Tables[0].DefaultView;

            fMoKhoaControl(true);
            clsdc.editGrid(grdXemDBG_View, false, null);
        }

        #endregion  

        
        #endregion

    }
}